import os
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse, reverse
from django.contrib.auth.decorators import login_required

staticdir = os.path.join(settings.BASE_DIR, 'static')
ext = ['css', 'js']

def list_dir(path):
    f_list = os.listdir(path)
    dlist = []
    flist = []

    if f_list:
        for i in f_list:
            if os.path.isdir(os.path.join(path, i)):
                if (path == staticdir or path.rstrip('/') == staticdir or path.rstrip('\\') == staticdir) and i == 'xadmin':
                    pass
                else:
                    dlist.append(i)
            else:
                if len(i.split('.')) > 1 and i.split('.')[-1] in ext:
                    flist.append(i)
    return dlist, flist

@login_required
def index(request):
    mbx = ['静态资源']
    dlist, flist = list_dir(staticdir)
    siteid = request.GET.get('siteid')

    return render(request, 'xadmin/staticfileprocess/index.html', locals())


@login_required
def opendir(request):
    siteid = request.GET.get('siteid')
    path = request.GET.get('path')
    dirname = request.GET.get('name')
    #dirpath = os.path.join(path, dirname)
    dirpath = '%s/%s' % (path, dirname)
    dirpath = dirpath.strip('/')
    path = os.path.join(staticdir, os.path.join(path, dirname))

    mbx = ['静态资源', dirname]
    dlist, flist = list_dir(path)
    return render(request, 'xadmin/staticfileprocess/index.html', locals())


@login_required
def openfile(request):
    siteid = request.GET.get('siteid')
    if request.method == 'GET':
        path = request.GET.get('path')
        filename = request.GET.get('name')
        dirpath = path
        file_path = os.path.join(staticdir, path, filename)

        f = open(file_path, 'r', encoding='UTF-8')
        code = f.read()

        f.close()
        mbx = ['静态资源', filename]
        return render(request, 'xadmin/staticfileprocess/code.html', locals())
    else:
        print(request.META.get("HTTP_USER_AGENT"))
        file_path = request.POST.get('file_path')
        code = request.POST.get('code')
        dirpath = request.POST.get('dir_path')
        for line in code:
            print(line)
        if file_path and code:
            with open(file_path, 'w', encoding='UTF-8') as f:
                f.write(code.replace('\n', ''))
        if '/' in dirpath:
            path = dirpath.split('/')[0]
            name = dirpath.split('/')[-1]
        else:
            path = ''
            name = dirpath
        return redirect('%s?siteid=%s&path=%s&name=%s' % (reverse('opendir'), siteid, path, name))